/**
 * PermissionFilter.java
 * 
 * Project: GWBS2009
 * 
 * Copyright Notice:
 * =============================================================================
 *    Copyright (c) 2007-2010 Shanghai Auto-Parts E-Procurement Co., Ltd.
 *        All rights reserved.
 *
 *    This software is the confidential and proprietary information of
 *        APEP Co., Ltd. ("Confidential Information").
 *        You shall not disclose such Confidential Information and shall use it
 *        only in accordance with the terms of the license agreement you entered
 *        into with APEP.
 *
 * Warning:
 * =============================================================================
 *
 */
package com.apep.permission;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import system.LoginContext;
import framework.core.DBConnection;
import framework.core.SrvContext;

public class PermissionFilter implements Filter {

	public static final int EIGHT_HOURS = 60 * 60 * 8;

	private Log logger = LogFactory.getLog(PermissionFilter.class);

	private final static String LOGIN_JSP = "system/login.jsp";

	private final static String ACTION_CODE = "action_code";
	private final static String LOGIN_ACTION_CODE = "login";

	public final static String COOKIE_USER_CODE_NAME = "usooiekc";
	public final static String COOKIE_PASSWORD_NAME = "osiekudhfk";

	public static final String EXCLUDE_SUFFIXS_NAME = "excludeSuffixs";

	private static final String[] DEFAULT_EXCLUDE_SUFFIXS = { ".js", ".css", ".jpg", ".gif", ".png", ".jpeg", ".bmp" };

	private static final String[] DEFAULT_EXCLUDE_URI = {"ApepSynService", "HTTPService","ProjectManagerServlet","ProductPictureShowServlet"};

	public void destroy() {

	}

	/* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		DBConnection con = null;
		HttpServletRequest servletRequest = (HttpServletRequest)request;
		LoginContext loginContext = (LoginContext)servletRequest.getSession().getAttribute("LoginContext");

		// 若已经登录，则进行下一步操作
		if(loginContext != null && loginContext.isLogin()) {
			logger.trace("用户已登录，进行下一步操作。");
			chain.doFilter(request, response);
			return;
		}

		// 若用户直接访问页面，则不判断，直接执行下一步操作
		String uri = servletRequest.getRequestURI();
		if(!needCheck(uri)) {
			chain.doFilter(request, response);
			return;
		}

		// 判断不需要模拟登录的方法、页面
		String tActionCode = request.getParameter(ACTION_CODE);
		if(tActionCode != null && LOGIN_ACTION_CODE.equals(tActionCode)) {
			logger.trace("用户执行登录操作。");
			chain.doFilter(request, response);
			return;
		}

		String userCode = CookieUtils.getValue(servletRequest, COOKIE_USER_CODE_NAME);
		String password = CookieUtils.getValue(servletRequest, COOKIE_PASSWORD_NAME);



		// 没有登录，进行模拟登录
		// Cookie中有用户名信息
		if(userCode != null && userCode.length() > 0) {

			try {
				logger.debug("用户没有登录，进行模拟登陆。");

				con = DBConnection.open();

				SrvContext context = SrvContext.getContext(servletRequest);

				if(LoginContext.login(con, context, userCode, password, false)) {
					logger.debug("用户模拟登录成功，进行下一步操作。");
					chain.doFilter(request, response);
					return;
				} else {
					logger.debug("模拟登录失败，转至登录页面。");
					redirectToLoginJSP(request);
				}
			} catch(Exception e) {
				logger.error(e.getLocalizedMessage(), e);
				redirectToLoginJSP(request);
			} finally {
				try {
					if(con != null && !con.isClosed()) {
						con.close();
					}
				} catch (Exception e) {
					logger.error(e.getLocalizedMessage(), e);
				}
			}

		} else {
			logger.debug("Cookie中没有有效的用户信息，转至登录页面。");
			redirectToLoginJSP(request);
		}
	}

	public void init(FilterConfig config) throws ServletException {
		String exludeSuffixsName = config.getInitParameter(EXCLUDE_SUFFIXS_NAME);
		setExludeSuffixsName(exludeSuffixsName);
	}

	public boolean needCheck(String uri) {

		if(uri == null) {
			return false;
		}

		String[] suffixsName = DEFAULT_EXCLUDE_SUFFIXS;
		if(getExludeSuffixsName() != null) {
			suffixsName = getExludeSuffixsName().split(",");
		}

		for(int i=0; i<suffixsName.length; i++) {
			if(uri.toLowerCase().indexOf(suffixsName[i].toLowerCase()) > 0) {
				return false;
			}
		}

		String[] excludeURI = DEFAULT_EXCLUDE_URI;
		if(getExcludeURI() != null) {
			excludeURI = getExcludeURI().split(",");
		}

		for(int i=0; i<excludeURI.length; i++) {
			if(uri.toLowerCase().indexOf(excludeURI[i].toLowerCase()) > 0) {
				return false;
			}
		}

		return true;
	}

	private void redirectToLoginJSP(ServletRequest request) {
		request.getRequestDispatcher(LOGIN_JSP);
	}

	private String mExludeSuffixsName;
	private String mExcludeURI;

	public String getExcludeURI() {
		return mExcludeURI;
	}

	public void setExcludeURI(String mExcludeURI) {
		this.mExcludeURI = mExcludeURI;
	}

	public String getExludeSuffixsName() {
		return mExludeSuffixsName;
	}

	public void setExludeSuffixsName(String mExludeSuffixsName) {
		this.mExludeSuffixsName = mExludeSuffixsName;
	}


}
